﻿using ArsenalManagement.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;

namespace ArsenalManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly ArsenalManagementContext _context;

        public HomeController(ArsenalManagementContext context, ILogger<HomeController> logger)
        {
            _context = context;
            _logger = logger;
        }

        public IActionResult Index()
        {
            Unity unity = new Unity();
            var userid = _context.Users.FirstOrDefault(u => u.Username == HttpContext.Session.GetString("user")).Id;

            unity.weapon = _context.Weapons.Where(w => w.Id == _context.Userinfos.FirstOrDefault(i => i.Id == userid).Primaryweapon);
            unity.vehicle = _context.Vehicles.Where(w => w.Id == _context.Userinfos.FirstOrDefault(i => i.Id == userid).Vehicle);
            unity.vessel = _context.Vessels.Where(w => w.Id == _context.Userinfos.FirstOrDefault(i => i.Id == userid).Vessel);
            

            return View(unity);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string id = HttpContext.Session.GetString("user");
            if (string.IsNullOrEmpty(id))
            {
                context.Result = new RedirectResult("../User/Login");
            }
            else
            {
                ViewData["username"] = id;
            }
            base.OnActionExecuting(context);
        }





        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}